package net.zoneland.zrdp.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import net.zoneland.zrdp.common.constant.HttpStatus;
import net.zoneland.zrdp.common.core.domain.model.LoginUser;
import net.zoneland.zrdp.common.exception.ServiceException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * 安全服务工具类
 *
 * @author zonevue
 */
public class SecurityUtils
{
    private static final Logger LOGGER = LoggerFactory.getLogger(SecurityUtils.class);
    private SecurityUtils() {
        throw new IllegalStateException("Utility class");
    }
    /**
     * 用户ID
     **/
    public static Long getUserId() {
        try {
            return getLoginUser().getUserId();
        } catch (final Exception e) {
            throw new ServiceException("获取用户ID异常", HttpStatus.UNAUTHORIZED, e);
        }
    }

    /**
     * 获取部门ID
     **/
    public static Long getDeptId() {
        try {
            return getLoginUser().getDeptId();
        } catch (final Exception e) {
            throw new ServiceException("获取部门ID异常", HttpStatus.UNAUTHORIZED, e);
        }
    }

    /**
     * 获取用户账户
     **/
    public static String getUsername() {
        try {
            return getLoginUser().getUsername();
        } catch (final Exception e) {
            throw new ServiceException("获取用户账户异常", HttpStatus.UNAUTHORIZED, e);
        }
    }
    public static String getUserNameDefaultAnonymous() {
        try {
            return getLoginUser().getUsername();
        } catch (final Exception e) {
            LOGGER.warn("获取用户登录名失败，可能是匿名访问！", e);
            return "Anonymous";
        }
    }

    /**
     * 获取用户
     **/
    public static LoginUser getLoginUser() {
        try {
            return (LoginUser) getAuthentication().getPrincipal();
        } catch (final Exception e) {
            throw new ServiceException("获取用户信息异常", HttpStatus.UNAUTHORIZED, e);
        }
    }

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(final String password) {
        final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }

    /**
     * 判断密码是否相同
     *
     * @param rawPassword 真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     */
    public static boolean matchesPassword(final String rawPassword, final String encodedPassword) {
        final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }


    /**
     * 解密
     * @param content: 待解密内容，是 BASE64 编码后的字节串
     * @param secretKey 密钥
     * @param iv 解密用iv
     * @return 解密后的明文，直接返回经 UTF-8 编码转换后的明文
     */
    public static String decryptAES(final String content, final String secretKey, final String iv) throws NoSuchPaddingException,
        NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException,
        InvalidAlgorithmParameterException {
        // 密文进行 BASE64 解密处理
        final byte[] contentDecByBase64 = Base64.getDecoder().decode(content);
        // 获得一个 SecretKeySpec
        final SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), "AES");
        // 获得加密算法实例对象 Cipher
        final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); //"算法/模式/补码方式"
        // 获得一个初始化 IvParameterSpec
        final IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());
        // 根据参数初始化算法
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
        // 解密
        return new String(cipher.doFinal(contentDecByBase64), StandardCharsets.UTF_8);
    }

    /**
     * 加密
     * @param content 待加密内容
     * @param secretKey 密钥
     * @param iv 加密用iv
     * @return 加密后的密文，BASE64 编码后的字符串
     */
    public static String encryptAES(final String content, final String secretKey, final String iv)
        throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException,
        BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException {

        // 将字符串转换为字节数组
        final byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8);
        // 获得一个 SecretKeySpec
        final SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), "AES");
        // 获得加密算法实例对象 Cipher
        final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); // "算法/模式/补码方式"
        // 获得一个初始化 IvParameterSpec
        final IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());
        // 根据参数初始化算法
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
        // 加密
        final byte[] encryptedBytes = cipher.doFinal(contentBytes);
        // 将加密后的字节数组进行 BASE64 编码处理
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    /**
     * 是否为管理员
     *
     * @param userId 用户ID
     * @return 结果
     */
    public static boolean isAdmin(final Long userId)
    {
        return userId != null && 1L == userId;
    }
}
